package top.codedance.iotp.tools.terminal.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.tools.terminal.TerminalApplication;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.InputEvent;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 *
 * @author xuedianfu
 */
public class AddOpc extends javax.swing.JDialog {
    
    public ClientPluginTester cpt;
    private DefaultTableModel tm;
    private String[] colums = new String[]{"数据"};
    private String[][] tableData = new String[][]{};
    private int rowIndex = -1;
    private OpcBrower opcBrower = null;

    /**
     * Creates new form AddOpc
     */
    public AddOpc(ClientPluginTester cpt, JSONObject initData) {
        super(cpt, true);
        this.cpt = cpt;
        initComponents();
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(this.cpt.getShellFrame());
        setMinimumSize(new Dimension(500, 600));
        setResizable(true);
        setTitle("代码飞舞采控系统-添加OPC");

        initResultTable();
        initRequesItemtOprationMenus();
        initEditData(initData);
    }

    public ClientPluginTester getClientPluginTester(){
        return this.cpt;
    }

    private void initEditData(JSONObject initData){
        if(initData != null){
            JSONObject client = initData.getJSONObject("client");
            jtf_id.setText(client.getString("id"));
            JSONArray tags = client.getJSONArray("tags");
            for (int i = 0;i < tags.size();i++){
                JSONObject jsonObject = tags.getJSONObject(i);
                tm.addRow(new String[]{jsonObject.toJSONString()});
            }
            rowIndex = initData.getIntValue("rowIndex");
        }
    }

    private void initResultTable(){
        tm = new DefaultTableModel(tableData, colums);
        jt_result.setModel(tm);
    }

    private JPopupMenu paramHelpJpm;

    private void initRequesItemtOprationMenus() {
        paramHelpJpm = new JPopupMenu();
        JMenuItem mi_del = new JMenuItem("删除");
        mi_del.addActionListener(e -> {
            int[] selectedRows = jt_result.getSelectedRows();
            Arrays.sort(selectedRows);
            for(int ii = selectedRows.length -1; ii >=0; ii--) {
                tm.removeRow(selectedRows[ii]);
            }
        });
        paramHelpJpm.add(mi_del, 0);
        jt_result.add(paramHelpJpm);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jtf_namespace = new javax.swing.JTextField();
        jtf_tag = new javax.swing.JTextField();
        jb_save = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jtf_id = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jt_result = new javax.swing.JTable();
        jb_add = new javax.swing.JButton();
        jb_clean = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jtf_ext = new javax.swing.JTextField();
        jb_browerTagTree = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("添加OPC");

        jLabel2.setText("命名空间：");

        jLabel3.setText("标签：");

        jtf_namespace.setText("2");
        jtf_namespace.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtf_namespaceKeyTyped(evt);
            }
        });

        jb_save.setText("保存为命令");
        jb_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_saveActionPerformed(evt);
            }
        });

        jLabel4.setText("Client id：");

        jtf_id.setText("0");
        jtf_id.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtf_idKeyTyped(evt);
            }
        });

        jt_result.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jt_result.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jt_resultMousePressed(evt);
            }
        });
        jt_result.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jt_resultPropertyChange(evt);
            }
        });
        jScrollPane1.setViewportView(jt_result);

        jb_add.setText("添加");
        jb_add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_addActionPerformed(evt);
            }
        });

        jb_clean.setText("清空");
        jb_clean.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_cleanActionPerformed(evt);
            }
        });

        jLabel5.setText("扩展：");

        jb_browerTagTree.setText("浏览节点...");
        jb_browerTagTree.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_browerTagTreeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(jtf_namespace))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(18, 18, 18)
                                .addComponent(jtf_id))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(42, 42, 42)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jtf_ext)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jtf_tag)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jb_browerTagTree))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(52, 52, 52)
                                        .addComponent(jb_add)
                                        .addGap(18, 18, 18)
                                        .addComponent(jb_save)
                                        .addGap(18, 18, 18)
                                        .addComponent(jb_clean)
                                        .addGap(0, 0, Short.MAX_VALUE))))))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(249, 249, 249)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel5)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jtf_id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jtf_namespace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jtf_tag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jb_browerTagTree)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jtf_ext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jb_add)
                    .addComponent(jb_save)
                    .addComponent(jb_clean))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private String getTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(new Date());
    }

    public void setTag(String tag){
        jtf_tag.setText(tag);
    }

    private void jb_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_saveActionPerformed
        JSONObject commandParams = new JSONObject();
        commandParams.put("plugin", Command.OPC_COMMAND);
        JSONArray data = new JSONArray();
        for(int i = 0; i < tm.getRowCount();i++){
            data.add(JSON.parseObject((String)tm.getValueAt(i, 0)));
        }
        JSONObject clientJo = new JSONObject();
        clientJo.put("id", Integer.valueOf(jtf_id.getText()));
        clientJo.put("tags", data);
        commandParams.put("client", clientJo);
        if(rowIndex < 0) {
            String defaultName = "OPC-" + getTime();
            String name = (String) JOptionPane.showInputDialog(this, "如需重新起名，请输入新的名称。", "保存命令", JOptionPane.QUESTION_MESSAGE, null, null, defaultName);
            if (name == null || name.isEmpty()) {
                name = defaultName;
            }
            cpt.addPluginParam(commandParams, name);
        }else{
            cpt.addPluginParam(commandParams, rowIndex);
        }
        setVisible(false);
    }//GEN-LAST:event_jb_saveActionPerformed

    private void jb_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_addActionPerformed
        if(jtf_tag.getText().isEmpty()){
            JOptionPane.showMessageDialog(rootPane, "标签不能为空。");
            return;
        }
        JSONObject jo = new JSONObject();
        jo.put("tag", jtf_tag.getText());
        try {
            jo.put("ns", jtf_namespace.getText());
        }catch (Exception e){
            TerminalApplication.syslogInfo(e.getMessage());
            JOptionPane.showMessageDialog(rootPane, "命名空间必须为数字。");
            return;
        }
        if(!jtf_ext.getText().isEmpty()){
            jo.put("ext", jtf_ext.getText());
        }
        tm.addRow(new String[]{jo.toJSONString()});
    }//GEN-LAST:event_jb_addActionPerformed

    private void jt_resultMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jt_resultMousePressed
        int mods = evt.getModifiers();
        if ((mods & InputEvent.BUTTON3_MASK) != 0) {
//            if (this.getExtendedState() == Frame.MAXIMIZED_BOTH) {
//                this.paramHelpJpm.show(this, evt.getX(), evt.getYOnScreen() + this.paramHelpJpm.getHeight() / 2);
//            } else {
                this.paramHelpJpm.show(this, evt.getX(), evt.getYOnScreen() - 180);
//            }
        }
    }//GEN-LAST:event_jt_resultMousePressed

    private void jb_cleanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_cleanActionPerformed
        for(int i = jt_result.getRowCount() -1; i >=0; i--) {
            tm.removeRow(i);
        }
    }//GEN-LAST:event_jb_cleanActionPerformed

    private void jb_browerTagTreeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_browerTagTreeActionPerformed
        if(opcBrower == null) {
            opcBrower = new OpcBrower(this);
            opcBrower.setLocationRelativeTo(this);
        }
        opcBrower.setClientId(this.jtf_id.getText());
        opcBrower.setVisible(true);
    }//GEN-LAST:event_jb_browerTagTreeActionPerformed

    private void jt_resultPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jt_resultPropertyChange

    }//GEN-LAST:event_jt_resultPropertyChange

    private void jtf_idKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtf_idKeyTyped
        JTextField jtf = (JTextField)evt.getSource();
        if (!TerminalApplication.numbers.contains(evt.getKeyChar())) {
            evt.consume();
        }
        try{
            Integer.parseInt(jtf.getText());
            if(jtf.getText().startsWith("0")){
                jtf.setText(jtf.getText().replaceAll("^0+", ""));
            }
        }catch (Exception e){
            jtf.setText("0");
        }
    }//GEN-LAST:event_jtf_idKeyTyped

    private void jtf_namespaceKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtf_namespaceKeyTyped
        jtf_idKeyTyped(evt);
    }//GEN-LAST:event_jtf_namespaceKeyTyped

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jb_add;
    private javax.swing.JButton jb_browerTagTree;
    private javax.swing.JButton jb_clean;
    private javax.swing.JButton jb_save;
    private javax.swing.JTable jt_result;
    private javax.swing.JTextField jtf_ext;
    private javax.swing.JTextField jtf_id;
    private javax.swing.JTextField jtf_namespace;
    private javax.swing.JTextField jtf_tag;
    // End of variables declaration//GEN-END:variables
}
